package ar.edu.caece.pl.asem.model.impl.treeelements;

import ar.edu.caece.pl.asem.temp.TemporalGenerator;

public class DivisionInt extends AbstractElement {

	private int tempResultDivInt; // propio para producto de enteros, se usa
									// para guardar el resultado de un producto
									// temporal.

	public DivisionInt() {
		this.label = "DIVISION_ENTERA";
	}

	public int getTemp() {
		return tempResultDivInt;
	}

	public void setTemp(int temp) {
		this.tempResultDivInt = temp;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof DivisionInt))
			return false;
		DivisionInt other = (DivisionInt) obj;
		if (label == null) {
			if (other.label != null)
				return false;
		} else if (!label.equals(other.label))
			return false;
		return true;
	}

	@Override
	public void generateASMCode() {
		StringBuffer sb = new StringBuffer();
		String term = null;

		AbstractElement dividendo = this.getChildren().get(0);
		AbstractElement divisor = this.getChildren().get(1);
		dividendo.parent = this;
		dividendo.generateASMCode();
		sb.append(dividendo.code);

		this.place = TemporalGenerator.getInstance().getActualTemporal();

		if (this.parent instanceof SumaInt || this.parent instanceof RestaInt
				|| this.parent instanceof SumaNat
				|| this.parent instanceof RestaNat) {
			TemporalGenerator.getInstance().releaseTemporal();
			term = "\t mov "
					+ TemporalGenerator.getInstance().getActualTemporal()
					+ ",ax \n";
		}

		sb.append(getDiv(this.place, this.place, divisor.getEnvName() + "_"
				+ divisor.getName()));

		if (term != null) {
			sb.append(term);
		}

		this.code = sb.toString();

	}

	private String getDiv(String label, String op1, String op2) {
		StringBuffer sb = new StringBuffer();
		sb.append("\t mov ax, " + op2 + " \n");
		sb.append("\t mov bx, ax \n");
		sb.append("\t mov dx, 0 \n");
		sb.append("\t mov ax, " + op1 + "\n");
		sb.append("\t idiv bx \n");
		sb.append("\t mov " + label + ",ax \n");
		return sb.toString();
	}

}
